package com.tonicgb.shared.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * @author zhaiyujin
 * @date 2021-09-07 15:18:37
 * @说明 配置任务使用自定义线程池来实现异步调用
 */
@Configuration
@EnableAsync
public class TaskExecutorConfig {

    //普通模式
    private final int taskCorePoolSize = 20; //核心线程池数量
    private final int taskMaxPoolSize = 100; //最大线程
    private final int taskQueueCapacity = 200; //缓存队列条数
    private final int taskKeepAliveSecond = 10; //允许的空闲时间
    private final String taskNamePrefix = "tonicgb-taskExecutor-"; //线程名称前缀

    @Bean("taskExecutor")
    public Executor taskExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(taskCorePoolSize);
        executor.setMaxPoolSize(taskMaxPoolSize);
        executor.setQueueCapacity(taskQueueCapacity);
        executor.setKeepAliveSeconds(taskKeepAliveSecond);
        executor.setThreadNamePrefix(taskNamePrefix);
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        return executor;
    }
}
